package com.example.managementjava.Leave;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/Leave")
public class Leave extends HttpServlet {
    public static List<LeaveNote> list = new ArrayList<>();

    @Override
    public void init(){
        list= DB_Leave.selectAlllist();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        resp.setContentType("text/json;charset=utf-8");
        //请求解决乱码
        req.setCharacterEncoding("utf-8");
        //响应解决乱码
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println("请假信息");
        for (LeaveNote i : list){
            writer.println(i.toString());
        }
//        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        resp.setContentType("text/html;charset=utf-8");
        //请求解决乱码
        req.setCharacterEncoding("utf-8");
        //响应解决乱码
        resp.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        String number = req.getParameter("学号");
        String gender = req.getParameter("性别");
        String phone = req.getParameter("联系电话");
        String special = req.getParameter("年级专业班级");
        String home = req.getParameter("宿舍");
        String date = req.getParameter("请假时间");
        String reason = req.getParameter("请假事由");
        String endtime = req.getParameter("销假时间");
        String way = req.getParameter("way");
        System.out.println(way);
        if(way!=null){
            String msg = req.getParameter("msg");
            DB_Leave.editLeave(msg);
            list= DB_Leave.selectAlllist();
        }
        else {
            LeaveNote leaveNote = new LeaveNote(name,number,gender,phone,special,
                    home,date,reason,endtime);
            String msg = "("+
                    "\""+name+"\""+","+"\""+number+"\""+","+"\""+gender+"\""+","+"\""+phone+"\""+","+"\""+special+"\""+","+"\""+home+"\""+","+"\""+
                    date+"\""+","+"\""+reason+"\""+","+"\""+endtime+"\""+
                    ")";
            DB_Leave.addLeave(msg);
            list = DB_Leave.selectAlllist();
            PrintWriter out = resp.getWriter();
            out.println("<html><head><title>签退验证</title> <meta http-equiv=\"refresh\" content=\"2;url="+req.getContextPath()+"\"></head>");
            out.println("<body>");
            out.println("<h1>提交成功:</h1>");
            out.println(leaveNote);
            out.println("</body></html>");
        }

    }
}
